//
//  WQRefreshControl.swift
//  sanwuWeibo
//
//  Created by 王先强 on 15/12/13.
//  Copyright © 2015年 王先强. All rights reserved.
//

import UIKit
let WQRefreshControlOffset: CGFloat = -60
class WQRefreshControl: UIRefreshControl {

    
    
    override func beginRefreshing() {
        super.beginRefreshing()
        refreshView.startAnimation()
    }
    
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.stopAnimation()
    }
    
    
    override init() {
        super.init()
        tintColor = UIColor.clearColor()
        setupUI()
        
    }

    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //重写frame属性也能实现KVO等效监听方法
//    override var frame: CGRect {
//        didSet{}
//    }
    
    
    
    private func setupUI() {
        addSubview(refreshView)
        refreshView.snp_makeConstraints { (make) -> Void in
            make.width.equalTo(200)
            make.height.equalTo(60)
            make.centerX.equalTo(self.snp_centerX)
            make.centerY.equalTo(self.snp_centerY)
        }
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
        
            self.addObserver(self, forKeyPath: "frame", options:[] , context: nil)
        }
        
    }
    
    deinit {
        removeObserver(self, forKeyPath: "frame")
    }
    
    //指示箭头的标志
    var rotateState = false
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        //过滤掉y>0的监听
        if frame.origin.y > 0 {
            return
        }
        
        
        
        if frame.origin.y < WQRefreshControlOffset && !rotateState  {
            print("旋转 由上到下")
            rotateState = true
            rotateArrow()
        }
        if frame.origin.y > WQRefreshControlOffset && rotateState {
            print("旋转 由下到上")
            rotateState = false
            rotateArrow()
        }
        
    }
    
    private func rotateArrow() {
        
        var rotateAngle = CGFloat(M_PI)
        rotateAngle += (rotateState ? -0.000001 : 0.000001)
        
        UIView.animateWithDuration(0.2) { () -> Void in
            self.refreshView.imageView.transform = CGAffineTransformRotate(self.refreshView.imageView.transform, rotateAngle)
//            self.refreshView.transform = CGAffineTransformTranslate(self.refreshView.transform, 0, -self.frame.origin.y)
        }
    }
    
    private lazy var refreshView: WQRefreshView = WQRefreshView()
}

class WQRefreshView: UIView {
   

    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        backgroundColor = UIColor.whiteColor()
//        backgroundColor = randomColor
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI() {
        
        
        addSubview(imageView)
        addSubview(refreshLabel)
        imageView.sizeToFit()
        refreshLabel.sizeToFit()
        
        
        imageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(-70)
            make.centerY.equalTo(self.snp_centerY)
        }
        refreshLabel.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self.snp_centerY)
            make.left.equalTo(imageView.snp_right).offset(10)
        }
        
    }
    
    func startAnimation() {
        imageView.image = UIImage(named: "tableview_loading")
        refreshLabel.text = "正在努力刷新数据..."
        let ani = CABasicAnimation(keyPath: "transform.rotation")
        ani.toValue = M_PI * 2
        ani.repeatCount = MAXFLOAT
        ani.removedOnCompletion = false
        ani.duration = 0.5
        imageView.layer.addAnimation(ani, forKey: nil)
    }
    func stopAnimation() {
        delay(0.5) { () -> () in
            self.imageView.layer.removeAllAnimations()
            self.imageView.image = UIImage(named: "tableview_pull_refresh")
            self.refreshLabel.text = "下拉加载更多微博..."
        }
    }
    
    lazy var imageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    lazy var refreshLabel = UILabel(title: "下拉加载更多微博...")
    
    
}

